<script setup>
import {ArrowUp, Back} from '@element-plus/icons-vue'
import {
  ref,
  onMounted,
  getCurrentInstance, watch,
} from 'vue'
import {useRouter, useRoute} from "vue-router";
import { ElMessage } from 'element-plus'
const count = ref(1)          // 数量默认值
const activeCollapse = ref([])// 折叠面板激活状态
const detailOpen = ref(false) // 明细展开状态

const toggleDetail = () => {
  detailOpen.value = !detailOpen.value
  if (detailOpen.value) activeCollapse.value = ['1']
  else activeCollapse.value = []
}
const global = getCurrentInstance().appContext.config.globalProperties;

// useRoute: 取路由参数
// useRouter: 1.编程式路由跳转，2.还有<router-link>方式

const router = useRouter();
const route = useRoute(); //路由参数(query/params) 包含在 route 对象中
const {query} = useRoute();

// 计算总价
const totalPrice = ref(0);

//定义返回后端的数据
const orderData =ref({
  //orderId:null,
  id:null, // 用于存储用户id
  pid: null,
  totalPrice: null
});

//演出信息
const performance = ref({
  pid: '',
  pname: '',
  purl: '',
  pdetail: '',
  pprice: 0, // 初始化为数字类型
  ptime: '',
  plocation: ''
})

//向后端发送请求，获取数据
global.$http.get(`/public/maoyanmovieproject/queryPerformanceById/${query.id}`)
    .then(resp => {
      console.log(resp.data);
      performance.value = resp.data; // 存入数组，如果直接用performances.value = [resp.data] 会覆盖数组，导致最终仅保留最后一次请求的结果
      // 确保pprice是数字类型
      performance.value.pprice = Number(performance.value.pprice);
      // 初始化总价
      totalPrice.value = performance.value.pprice * count.value;
    }).catch(err => {
  console.error('获取演出信息失败:', err);
  // 可以添加错误提示
})

// 监听count或pprice变化，实时更新总价（关键修复）
watch([() => count.value, () => performance.value.pprice], () => {
  totalPrice.value = performance.value.pprice * count.value;
});


// 新增：用于存储后端返回的自增orderId
const orderId = ref(null);

//编程式路由跳转，返回上一页
const testRouter = () => {
  router.go(-1) // history.back(), history.forward(), history.go(-1|1)
}

// 确认购买按钮事件
const confirmPurchase = () => {
  // 这里可以添加购买逻辑
  //console.log(`购买${count.value}张票，总价：${totalPrice.value}`);
  // 可以跳转到支付页面等
  // router.push({ name: 'payment', query: { pid: performance.value.pid, count: count.value } });
  //在浏览器上显示信息
  ElMessage(`购买${count.value}张票，总价：¥${totalPrice.value}`)
  /**
   * 将数据写入后端订单数据库performance_order_form
   */
  console.log('1111111')
  console.log(localStorage.getItem('userId'))
//1.准备返回给后端的数据（PerformanceOrder对象）
  orderData.value={
    //顶单id不用传，我设置了自增
    //orderId:null,
    id:localStorage.getItem('userId'),/*localStorage.get,  */ //用户id,这里写死了
    pid:performance.value.pid ,//演出id
    totalPrice:totalPrice.value   // 这里使用实时计算的总价
  }


//发送创建演出订单请求
  global.$http.post('/public/maoyanmovieproject/addPerformanceOrder',orderData.value)
      .then(resp=>{
        if(resp.data==='success'){
          //在浏览器上显示信息
          ElMessage(`购买成功!`);
          orderId.value = resp.data?.data?.orderId;  // 根据后端实际返回结构修改
        }else{
          //在浏览器上显示信息
          ElMessage(`购买失败!`);
        }}).catch(err => {
    console.error('购买失败:', err);
  })
};

// 点击查看订单按钮事件
const checkOrder = () => {
  // 判断是否已点击确认（通过orderId是否存在判断）
  //if (orderId.value!=null) {
    // 如果已点击确认，执行后续代码，跳转页面
    console.log(`查看订单成功！`);
    // 跳转到订单页面
    router.push({ name: 'performance-order', query: {
        pid: performance.value.pid,
        count: count.value,
        userId:orderData.value.id,//用户id
        orderId: orderId.value} });
 /* }else{
    // 未点击确认，提示并阻止跳转
    ElMessage({
      message: '请先点击确认',
      type: 'warning'
    });
  }*/
};

//点击“特惠单人票”，实现购票数量加1
const buyTicket=()=>{
  count.value=count.value+1;
}

</script>


<template>
  <div class="ticket-container">
    <!-- 返回图标   -->
    <el-icon style="font-size: xx-large; cursor: pointer; margin-bottom: 20px;" @click="testRouter">
      <Back/>
    </el-icon>

    <!-- 票档区域 -->
    <div class="ticket-section">
      <h3> {{performance.pname}}</h3>
      <div class="myImage">
      <el-image :src="performance.purl"/>
      </div>
      <br>
      <h3>票档</h3>
      <el-card class="ticket-card" @Click="buyTicket">
        <div class="price-row">
          <el-col :span="16">
            <el-text class="current-price" >特惠单人票 ¥{{ performance.pprice }}</el-text>
          </el-col>
        </div>
      </el-card>
      <div class="desc">
        <span>入场一人一票，凭票入场</span>
      </div>
    </div>

    <!-- 数量选择 -->
    <div class="quantity-section">
      <el-row>
        <el-col :span="12">
          <span class="label">数量</span>
          <span class="limit">每单限购6份</span>
        </el-col>
        <el-col :span="12">
          <el-input-number v-model="count" :min="1" :max="6"/>
        </el-col>
      </el-row>
    </div>

    <!-- 总计 & 明细 -->
    <div class="total-section">
      <el-row>
        <el-col :span="16">
          <span class="total-label">总计：</span>
          <el-text class="total-price"> ¥{{ totalPrice }}</el-text>
        </el-col>
        <el-col :span="8">
          <el-button type="text" @click="toggleDetail">
            明细
            <el-icon :class="{ rotate: detailOpen }">
              <ArrowUp/>
            </el-icon>
          </el-button>
          <el-collapse v-model="activeCollapse">
            <el-collapse-item name="1" >
              <div class="detail-content">
                <!-- 明细内容 -->
                <p>{{ performance.pname }}: ¥{{ performance.pprice }} × {{ count }}</p>
                <p>总计: ¥{{ totalPrice }}</p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-col>
      </el-row>
    </div>

    <!-- 确认按钮 -->
    <el-row>
      <el-col :span="18" class="ack-button">
        <el-button type="primary" @click="confirmPurchase" >确认</el-button>
      </el-col>
      <el-col :span="6" class="ack-button">
        <el-button type="primary" @click="checkOrder" >查看订单</el-button>
      </el-col>
    </el-row>
  </div>
</template>


<style scoped>
/* 自定义样式（示例） */
.ticket-container {
  padding: 20px;
}
/*确认按钮*/
.ack-button{
  display: flex;
  align-items: center;     /* 水平居中（图标和文字都居中） */
}

.ticket-card {
  width: 320px;
  margin: 10px 0;
}

.current-price {
  color: red;
  font-size: 18px;
}

.original-price {
  color: #999;
}

.desc {
  display: flex;
  align-items: center;
  color: #666;
}

.desc el-icon {
  margin-right: 5px;
  color: #999;
}

.quantity-section {
  margin: 20px 0;
}

.label {
  font-weight: bold;
  margin-right: 10px;
}

.limit {
  color: #999;
  font-size: 12px;
}

.total-price {
  color: red;
  font-size: 18px;
  margin: 0 5px;
}

.total-original {
  color: #999;
}

.confirm-section {
  text-align: right;
  margin-top: 20px;
}

.detail-content {
  padding: 10px;
}

.rotate {
  transform: rotate(180deg);
}
.myImage{
  text-align: center; /* 新增：使内部 inline 元素（图片）水平居中 */
}
</style>
